package com.sd.coupon.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sd.coupon.entity.ItemCoupon;
import com.sd.coupon.model.req.GoodsPageReq;
import com.sd.coupon.model.req.GoodsReq;
import com.sd.coupon.service.IItemCouponService;
import com.sd.coupon.service.MItemCouponService;
import com.sd.coupon.util.Contant;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class MItemCouponServiceImpl implements MItemCouponService {

    @Resource
    IItemCouponService itemCouponService;

    @Override
    public IPage<ItemCoupon> getItemCouponPage(GoodsPageReq req) {

        if (req == null) {
            req = new GoodsPageReq();
            req.setCurrent(1L);
            req.setSize(10L);
        }

        QueryWrapper<ItemCoupon> query = buildPageQueryWrapper(req);
        IPage<ItemCoupon> res = itemCouponService.page(new Page<ItemCoupon>(req.getCurrent(), req.getSize()), query);
        List<ItemCoupon> list = res.getRecords();
        for (int i = 0; i < list.size(); i++) {
            ItemCoupon coupon = list.get(i);
        }
        return res;
    }

    @Override
    public ItemCoupon getItemCoupon(GoodsReq req) {
        if (req == null || req.getNumIid() == null) {
            return null;
        }
        QueryWrapper<ItemCoupon> queryWapper = new QueryWrapper<>();
        queryWapper.eq(Contant.ItemCoupon.NUMIID, req.getNumIid());
        ItemCoupon res = itemCouponService.getOne(queryWapper);
        return res;
    }

    private QueryWrapper<ItemCoupon> buildPageQueryWrapper(GoodsPageReq req) {

        QueryWrapper<ItemCoupon> query = new QueryWrapper<ItemCoupon>();
        if (req == null) {
            return query;
        }

        //根据种类查询商品
        if (req.getCid() != null) {
            query.eq(Contant.ItemCoupon.CATEGORY, req.getCid());
        }

        //根据关键词查询商品
        if (!StringUtils.isEmpty(req.getKeyWord())) {
            query.like(Contant.ItemCoupon.TITLE, req.getKeyWord());
        }

        if (req.getNumIidList() != null && req.getNumIidList().size() > 0) {
            query.in(Contant.NUMIID, req.getNumIidList());
        }

        //排序
        if (!StringUtils.isEmpty(req.getSort())) {
            query.orderByDesc(req.getSort());
        } else {
//            query.orderByDesc(Contant.ItemCoupon.sort);
        }
        return query;
    }
}
